package com.cust.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cust.sky.context.BaseContext;
import com.cust.sky.entity.AddressBook;
import com.cust.sky.mapper.AddressBookMapper;
import com.cust.sky.service.AddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author lei
 * @since 2024-07-10
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<AddressBook> findAddressBookByUserId(Long userId) {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, userId);
        List<AddressBook> addressBookList = baseMapper.selectList(wrapper);
        return addressBookList;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void saveAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        baseMapper.insert(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        //把当前用户的地址簿修改为非默认地址
        List<AddressBook> addressBookList = baseMapper.selectList(new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId, BaseContext.getCurrentId()));
        for (AddressBook addressBook1 : addressBookList) {
            addressBook1.setIsDefault(0);
            baseMapper.updateById(addressBook1);
        }

        //将当前地址改为默认地址
        addressBook.setIsDefault(1);
        baseMapper.updateById(addressBook);
    }

    /**
     * 查询当前用户的默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getIsDefault, 1);
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        AddressBook addressBook = baseMapper.selectOne(wrapper);
        return addressBook;
    }
}
